﻿using System;
using System.Xml;
using Hvam.SharePoint.Search.Query.Site.Models;
using Microsoft.Office.Server.Search.Query;
using Microsoft.SharePoint.Utilities;

namespace Hvam.SharePoint.Search.Query.Site
{
    public sealed class SiteSearchRuntime : LocationRuntime
    {
        public override XmlDocument SendRequest(string query)
        {
            using (new SPMonitoredScope("SiteSearchRuntime::SendRequest"))
            {
                Location.TotalResults = 0;
                Location.TotalResultsIncludingDuplicates = 0;
                Location.ReturnedResults = 0;

                // Get empty result
                var xmlDocument = new SiteSearchResults().GetXmlDocument();
                
                if (string.IsNullOrEmpty(query))
                {
                    return xmlDocument;
                }

                try
                {
                    var results = SiteSearchTools.GetResults(query, Location);
                    if (results == null)
                    {
                        return xmlDocument;
                    }

                    Location.TotalResults = results.TotalResults;
                    Location.TotalResultsIncludingDuplicates = results.TotalResults;
                    Location.ReturnedResults = results.NumberOfResults;

                    return results.GetXmlDocument();
                }
                catch (Exception e)
                {
                    Logger.Current.Trace(e);
                }
                return xmlDocument;
            }
        }
    }
}
